import { Request, Response } from 'express';
import jobLogService from '@/services/monitor/jobLog.service';
import ApiResponse from '@/utils/api/api-response.util';
import { Log, BusinessType } from '@/decorators/Log';
import ExcelUtil from '@/utils/excel/excel.util';
import { getLogger } from '@/utils/logger';
import { AuthRequest } from '@/types';

// 创建模块专用的日志记录器
const consoleLogger = getLogger("joblog-controller");
const logger = getLogger("joblog-controller", {
	console: false,
});

/**
 * 定时任务日志控制器
 */
class JobLogController {
  /**
   * 查询定时任务日志列表
   * @param req 请求对象
   * @param res 响应对象
   */
  public async list(req: Request, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("获取定时任务日志列表请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      const query = {
        jobName: req.query.jobName as string,
        jobGroup: req.query.jobGroup as string,
        status: req.query.status as string,
        params: {
          beginTime: req.query.beginTime as string,
          endTime: req.query.endTime as string
        },
        pageNum: parseInt(req.query.pageNum as string) || 1,
        pageSize: parseInt(req.query.pageSize as string) || 10
      };
      
      const { rows, total } = await jobLogService.selectJobLogList(query);
      
      // 结果日志
      logger.info("获取定时任务日志列表成功", {
        response: {
          total,
          count: rows.length,
          pageNum: query.pageNum,
          pageSize: query.pageSize,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.page(res, rows, total, query.pageNum, query.pageSize);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`查询调度日志失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '查询失败');
      }
    }
  }

  /**
   * 删除定时任务日志
   * @param req 请求对象
   * @param res 响应对象
   */
  @Log({ title: '调度日志', businessType: BusinessType.DELETE })
  public async remove(req: AuthRequest, res: Response) {
    try {
      const jobLogIds = req.params.jobLogIds.split(',').map(id => parseInt(id));
      const operator = req.user?.userName || 'admin';
      
      // 请求日志
      consoleLogger.info("删除定时任务日志请求", {
        params: req.params,
        jobLogIds,
        operator,
      });
      
      const result = await jobLogService.deleteJobLogByIds(jobLogIds);
      
      // 结果日志
      logger.info("删除定时任务日志成功", {
        response: {
          jobLogIds,
          result,
        },
        operator,
      });
      
      ApiResponse.success(res, result, '删除成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`删除调度日志失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '删除失败');
      }
    }
  }

  /**
   * 清空定时任务日志
   * @param req 请求对象
   * @param res 响应对象
   */
  @Log({ title: '调度日志', businessType: BusinessType.CLEAN })
  public async clean(req: AuthRequest, res: Response) {
    try {
      const operator = req.user?.userName || 'admin';
      
      // 请求日志
      consoleLogger.info("清空定时任务日志请求", {
        operator,
      });
      
      await jobLogService.cleanJobLog();
      
      // 结果日志
      logger.info("清空定时任务日志成功", {
        operator,
      });
      
      ApiResponse.success(res, null, '清空成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`清空调度日志失败: ${error instanceof Error ? error.message : String(error)}`, {
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '清空失败');
      }
    }
  }

  /**
   * 导出定时任务日志
   * @param req 请求对象
   * @param res 响应对象
   */
  @Log({ title: '调度日志', businessType: BusinessType.EXPORT })
  public async export(req: Request, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("导出定时任务日志请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      const query = {
        jobName: req.query.jobName as string,
        jobGroup: req.query.jobGroup as string,
        status: req.query.status as string,
        params: {
          beginTime: req.query.beginTime as string,
          endTime: req.query.endTime as string
        }
      };
      
      const { rows } = await jobLogService.selectJobLogList({ ...query, pageNum: 1, pageSize: Number.MAX_SAFE_INTEGER });
      
      const fields = [
        { header: '日志编号', key: 'jobLogId', width: 10 },
        { header: '任务名称', key: 'jobName', width: 20 },
        { header: '任务组名', key: 'jobGroup', width: 15 },
        { header: '调用目标字符串', key: 'invokeTarget', width: 30 },
        { header: '日志信息', key: 'jobMessage', width: 30 },
        { header: '执行状态', key: 'status', width: 10, formatter: (value: string) => value === '0' ? '正常' : '失败' },
        { header: '异常信息', key: 'exceptionInfo', width: 30 },
        { header: '执行时间', key: 'createTime', width: 20, type: 'datetime' }
      ];
      
      await ExcelUtil.exportToResponse(
        res,
        rows,
        fields,
        `job_log_${Date.now()}`,
        '调度日志'
      );
      
      // 结果日志
      logger.info("导出定时任务日志成功", {
        response: {
          count: rows.length,
        },
        operator: req.user?.userName || 'unknown',
      });
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`导出调度日志失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '导出调度日志失败', 500);
      }
    }
  }

  /**
   * 查询定时任务日志详情
   * @param req 请求对象
   * @param res 响应对象
   */
  public async getInfo(req: Request, res: Response) {
    try {
      const jobLogId = parseInt(req.params.jobLogId);
      
      // 请求日志
      consoleLogger.info("获取定时任务日志详情请求", {
        params: req.params,
        jobLogId,
        operator: req.user?.userName || 'unknown',
      });
      
      // 检查jobLogId是否为有效数字
      if (isNaN(jobLogId) || jobLogId <= 0) {
        consoleLogger.warn('获取定时任务日志详情参数无效', { jobLogId: req.params.jobLogId });
        ApiResponse.error(res, '无效的日志ID', 400);
        return;
      }
      
      const jobLog = await jobLogService.selectJobLogById(jobLogId);
      
      if (!jobLog) {
        consoleLogger.warn('获取定时任务日志详情 - 日志不存在', { jobLogId });
        ApiResponse.error(res, '日志不存在', 404);
        return;
      }
      
      // 结果日志
      logger.info("获取定时任务日志详情成功", {
        response: {
          jobLogId,
          jobName: jobLog.jobName,
          status: jobLog.status,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, jobLog);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`查询调度日志详情失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '查询失败');
      }
    }
  }
}

export default new JobLogController(); 